<?php
class Account_resource_model extends MY_Model
{
	public
		$table = 'account_resources',
		$prKey = 'id'
	;

	function __construct()
	{
		parent::__construct();

		$this->fields = array(
			'id' 			=> '',
			'controller'	=> T_('Controller'),
			'action'		=> T_('Action'),
			'description'	=> T_('Description'),
			'name'			=> T_('Resource'),
			'parent'		=> T_('Parent Resource'),
		);

		$this->rules = array(
			'controller'	=> "trim|strip_tags|max_length[64]",
			'action'		=> "trim|strip_tags|max_length[64]",
			'description'	=> "trim|strip_tags|max_length[255]",
			'category'		=> "trim|strip_tags|required|max_length[128]",
			'parent'		=> "trim|strip_tags|integer",
		);
	}
	
	function search($config = array())
	{
		$order = $this->input->get_post('order');

		// main sql		
		$sql = 'SELECT *';
		$sql .= ' FROM '.$this->table.' r';
		$sql .= ' WHERE 1 = 1';  
		
		switch ($order)
		{			
			default:
				$sql .= ' ORDER BY r.controller, r.id';
				$direction = 'DESC';
		}
		
		$this->data['list'] = $this->db->query($sql)->result(); 
	}	
	
	function getAll()
	{	
		$sql = 'SELECT * FROM '.$this->table.' ORDER BY id';  
		$query = $this->db->query($sql);
		
		$data = array();
		
		foreach ($query->result() as $row)
		{
			$data[$row->id] = $row; 
		}
				
		return $data; 
	}	

	function getControllers()
	{	
		$sql = 'SELECT DISTINCT controller FROM "'.$this->table.'" ORDER BY controller';  
		$data = $this->db->query($sql)->result();
	
		return $data; 
	}	
	
	function delete($items_serialized = null)
	{
		$items = explode("&", $items_serialized);
		
		$report = "";
		foreach ($items as $id)
		{	
			$data = $this->account_resource_model->get($id);
			
			$res = $this->db->delete($this->table, array($this->prKey => $id));
 			$this->db->delete('account_permissions', array('id_account_resources' => $id));
			
			if (is_null($res))
			{
				$this->log->writeMessage('error', T_('Error. Ресурс не удален.'));
				$report .= ",0"; // don't deleted				
			}				
			else
			{
				$this->log->writeMessage('done', T_('Ресурс удален.'));
				$report .= ",1"; // deleted
				
		        $log['id_admins'] = $this->auth->getID();
		        $log['message']   = T_('Ресурс <span class="green">'). $data['description'] . T_('</span> удален.');
		        $log['location']  = $_SERVER['REQUEST_URI'];
		        $log['data']      = serialize($data);
		        $this->watchdog_model->insert($log);					
			}							
		}
		
		return substr($report, 1);
	}
		
}
?>